/**
 * A closure library for websocket.
 */
var ws = function() {
	var s = null;
	var self = this;
	window.onunload = function(){
		if(s)
			self.stop();
	};

	var logger = function(level, str) {
		if(typeof(level) == 'string' && typeof(str) == 'string') {
			if(window.console) {
				console.log("["+level+"] ws => "+str);
			}
		}
	};

	
	return {
		start: function(uri, funcs, subprotocol){
			// check WebSocket is supported or not.
			if(!window.WebSocket) {
				alert('This browser does not support WebSocket');
				return false;
			}
			
			
			// verify parameters.
			if(!(typeof(uri) == 'string' && uri.match(/^wss?(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)$/))) {
				logger('warn', 'start:: uri is invalid');
				return false;
			}
			if(!(typeof(funcs) == 'object' && funcs.onmessage && typeof(funcs.onmessage) == 'function')) {
				logger('warn', 'start:: funcs is invalid');
				return false;
			}
			subprotocol = typeof(subprotocol) == 'string' && subprotocol.length > 0 ? subprotocol : 'none';
			
			
			// start HandShake.
			s = new WebSocket(uri, subprotocol);

			s.onopen = function(e) {
				s.onmessage = function(e) {
					funcs.onmessage(e.data);
				}
				if(funcs.onopen && typeof(funcs.onopen) == 'function')
					funcs.onopen(e);
			}
			
			s.onerror = function(e) {
				if(funcs.onerror && typeof(funcs.onerror) == 'function')
					funcs.onerror(e);
			};
			
		},
		send : function(mesg) {
			if(s) {
				mesg.replace(/</g, '&lt;').replace(/>/g, '&gt;');
			
				s.send(mesg);
			}
		},
		stop: function(){
			if(s) {
				s.close();
				s = null;
			}
		}
	}
}();


/**
 * Nerin interface
 */
var controller = function(message) {
	var commands = { 
		left: function(){
			Nerine.prevPage();
		},
		right: function() {
			Nerine.nextPage();
		},
		up: function() {
			Nerine.indexMode();
		}
	};

	var logger = function(level, str) {
		if(typeof(level) == 'string' && typeof(str) == 'string') {
			if(window.console) {
				console.log("["+level+"] "+str);
			}
		}
	};
	
	if( message in commands && typeof(commands[message]) == 'function') {
		logger('DEBUG', message);
		commands[message]();
	} else {
		logger('DEBUG', 'unknown '+message);
	}
}


/**
 * Main
 */
$('document').ready(function(){
	ws.start('ws://'+location.host+'/iphoneif', {
		onmessage: controller
	});
});
